{include file="common/head"}
<style>
  .search-container {
    padding: 20px;
  }

  .layui-form-label {
    width: 100px;
  }
</style>
<div class="search-container layui-form" lay-filter="search">
  <div class="layui-inline">
    <div class="layui-input-wrap">
      <div class="layui-input-prefix">
        <i class="layui-icon layui-icon-tabs"></i>
      </div>
      <input type="text" name="content" id="content" value="" placeholder="内容" class="layui-input" lay-affix="clear">
    </div>
  </div>
  <div class="layui-inline">
    <label class="layui-form-label">发布时间</label>
    <div class="layui-inline" id="ID-laydate-range">
      <div class="layui-input-inline">
        <input type="text" autocomplete="off" id="ID-laydate-start-date" class="layui-input" placeholder="开始日期">
      </div>
      <div class="layui-form-mid">-</div>
      <div class="layui-input-inline">
        <input type="text" autocomplete="off" id="ID-laydate-end-date" class="layui-input" placeholder="结束日期">
      </div>
    </div>
  </div>
  <div class="layui-inline">
    <div class="layui-clear">
      <button style="float: right;" class="layui-btn layui-btn-sm layui-bg-blue" id="search">搜索文章</button>
    </div>
  </div>
</div>

<div class="cate-child-nav layui-btn-container" style="margin-top: 10px;" id="cate-child-nav">
</div>
<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm layui-bg-black" id="dropBtn">
      操作
      <i class="layui-icon layui-icon-down layui-font-12"></i>
    </button>
    <button class="layui-btn layui-btn-sm layui-bg-purple" id="dropdownButton">
      数据筛选
      <i class="layui-icon layui-icon-down layui-font-12"></i>
    </button>
    <button class="layui-btn layui-btn-sm layui-bg-red" id="delCheck" lay-event="delCheck">删除选中</button>
  
</div>
</script>
<script type="text/html" id="barDemo">
  <div class="layui-clear-space">
    <a class="layui-btn layui-btn-xs layui-bg-orange" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-bg-gray" lay-event="more">
      更多 
      <i class="layui-icon layui-icon-down"></i>
    </a>
    
  </div>

</script>
{include file="common/bottom"}
<script>
  layui.use(['table', 'dropdown'], function () {
    var table = layui.table;
    var dropdown = layui.dropdown;
    var laydate = layui.laydate;
    var $ = layui.$
    let delObj = []

    laydate.render({
      elem: '#ID-laydate-start-date',
    });
    laydate.render({
      elem: '#ID-laydate-end-date',
    });


    $('#search').click(() => {
      let title = $('#title').val()
      let content = $('#content').val()
      let start = $('#ID-laydate-start-date').val()
      let end = $('#ID-laydate-end-date').val()
      if (title == '' && content == '' && start == '' && end == '') {
        table.reload('test', { where: { type: '' } })
      } else {
        table.reload('test', {
          where: {
            title: title
            , content: content
            , begin_time: start
            , end_time: end
            , type: 'search'
          },
        })
      }

    })

    // 创建渲染实例
    table.render({
      elem: '#test',
      url: '/admin/article/list',
      toolbar: '#toolbarDemo',

      parseData: function (res) { // res 即为原始返回的数据
        return {
          "code": res.code, 
          "msg": res.msg, // 解析提示文本
          "count": res.data.count, // 解析数据长度
          "data": res.data.data.data
        };
      },
      defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
        title: '提示',
        layEvent: 'LAYTABLE_TIPS',
        icon: 'layui-icon-tips',
        onClick: function (obj) { // 2.9.12+
          layer.alert('自定义工具栏图标按钮');
        }
      }],
      height: 'full',
      css: [
        '.layui-table-tool-temp{padding-right: 145px;}'
      ].join(''),
      cellMinWidth: 80,
      totalRow: true, // 开启合计行
      page: true,
      cols: [[
        { type: 'checkbox' },
        { field: 'id', width: 80, title: 'ID', sort: true },
        { field: 'sort', width: 80, title: '排序', sort: true, edit: 'number', expandedMode: 'tips' },
        { field: 'title', width: 130, title: '标题' },
        {
          field: 'content', title: '内容', width: 300, templet: function (d) {
            function htmlToText(info) {
              return info
                .replace(/<[^>]*>/g, '')
                .replace(/&nbsp;/gi, ' ')
                .replace(/<br\s*\/?>/gi, '\n')
                ;
            }
            let imgRegex = /<img\b[^>]*>/gi;
            let p = /.*img.*/
            let ctn = d.content, replacedContent
            if (p.test(d.content)) {
              ctn = d.content.replace(imgRegex, '[图片]');
            }
            return htmlToText(ctn).substring(0, 20) + '...'
          }
        },
        {
          field: 'status', title: '状态', width: 80, templet: function (d) {
            if (d.status == 1) {
              return '<span class="layui-badge layui-bg-blue">正常</span>'
            } else if (d.status == 0) {
              return '<span class="layui-badge layui-bg-orange">待审核</span>'
            } else {
              return '<span class="layui-badge">封禁</span>'

            }
          }
        },
        { field: 'heat', title: '热度', width: 80, sort: true },
        {
          field: 'is_top', title: '是否置顶', width: 100, templet: function (d) {
            if (d.is_top == 1) {
              return '<span class="layui-font-12 layui-font-blue">是</span>'
            } else {
              return '<span class="layui-font-12 layui-font-gray">否</span>'

            }
          }
        },
        {
          field: 'is_hot', title: '是否加精', width: 100, templet: function (d) {
            if (d.is_hot == 1) {
              return '<span class="layui-font-12 layui-font-blue">是</span>'
            } else {
              return '<span class="layui-font-12 layui-font-gray">否</span>'

            }
          }
        },
        { field: 'user_id', width: 80, title: '用户名' },
        {
          field: 'tap_id', title: '标签', width: 150, templet: function (d) {
            let html = ''
            if (typeof d.tap_id == 'string') {
              return '<span class="layui-badge-rim">无</span>'
            } else {
              d.tap_id.forEach((el) => {
                if (el != null) {
                  html += `<span class="layui-badge-rim">${el}</span>`
                }
              })
              return html
            }
          }
        },

        { field: 'create_time', title: '发布时间', width: 150 },
        { title: '操作', width: 134, minWidth: 125, toolbar: '#barDemo' }
      ]],
      done: function () {
        var id = this.id;
        dropdown.render({
          elem: '#dropBtn', // 可绑定在任意元素中，此处以上述按钮为例
          data: [{
            id: 'add',
            title: '添加文章'
          }, {
            id: 'examine',
            title: '一键审核'
          },],
          // 菜单被点击的事件
          click: function (obj) {
            var checkStatus = table.checkStatus(id)
            var data = checkStatus.data; // 获取选中的数据
            switch (obj.id) {
              case 'add':
                layer.open({
                  title: '添加文章'
                  , area: ['80%', '80%']
                  , type: 2
                  , shadeClose: true
                  , maxmin: true
                  , anim: 0
                  , content: '/admin/article/add'
                })
                break
              case 'examine':
                var getData = table.getData(id);
                let idArr = []
                layer.confirm('确定要一键审核吗？', (res) => {
                  $.get('/admin/article/examineAll', (res) => {
                    if (res.code == 200) {
                      layer.msg('操作成功', { icon: 6, time: 1200 })
                      table.reload('test', { scrollPos: 'fixed', })
                    } else {
                      layer.msg('操作失败', { icon: 5, time: 1200 })
                    }
                  })
                })
                break

            }
          }
        })
        dropdown.render({
          elem: '#dropdownButton', // 可绑定在任意元素中，此处以上述按钮为例
          data: [{
            id: 'all',
            title: '展示全部'
          }, {
            id: 'top',
            title: '置顶文章'
          }, {
            id: 'hot',
            title: '加精文章'
          }, {
            id: 'heat',
            title: '高浏览[>100]'
          },],
          // 菜单被点击的事件
          click: function (obj) {
            var checkStatus = table.checkStatus(id)
            var data = checkStatus.data; // 获取选中的数据
            switch (obj.id) {
              case 'top':
                table.reload('test', { where: { where: { is_top: 1 } } })
                break
              case 'hot':
                table.reload('test', { where: { where: { is_hot: 1 } } })
                break
              case 'heat':
                table.reload('test', { where: { where: { heat: '100' } } })
                break
              case 'all':
                table.reload('test', { where: {} })
                break

            }
          }
        })

      },
      error: function (res, msg) {
        console.log(res, msg)
      }


    });

    // 工具栏事件
    table.on('toolbar(test)', function (obj) {
      var id = obj.config.id;
      var checkStatus = table.checkStatus(id);
      var othis = lay(this);
      switch (obj.event) {
        case 'add':
          layer.open({
            title: '添加文章'
            , area: ['80%', '80%']
            , type: 2
            , shadeClose: true
            , maxmin: true
            , anim: 0
            , content: '/admin/article/add'
          })
          break

        case 'delCheck':
          var data = checkStatus.data;
          var delId = ''
          data.forEach((el) => {
            delId += el.id + ','
          })
          layer.confirm('确定要删除选中的文章吗？', {
            btn: ['确定', '取消'],
          }, function () {
            layer.msg('操作成功', { icon: 6 })
            table.reload('test')
            $.post('/admin/article/del', { id: delId }, (res) => {
              layer.msg('操作成功', { icon: 6 })
              table.reload('test')
            })

          })

          break
        case 'examine':
          var getData = table.getData(id);
          layer.confirm('确定要一键审核吗？', (res) => {
            $.get('/admin/article/examineAll', (res) => {
              if (res.code == 200) {
                layer.msg('操作成功', { time: 1200 })
                table.reload('test', { scrollPos: 'fixed', })
              } else {
                layer.msg('操作失败', { time: 1200 })
              }
            })
          })
          break;
      };
    });
    // 表头自定义元素工具事件 --- 2.8.8+
    table.on('colTool(test)', function (obj) {
      var event = obj.event;
      if (event === 'email-tips') {
        layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
          title: '当前列属性配置项'
        });
      }
    });

    // 触发单元格工具事件
    table.on('tool(test)', function (obj) { // 双击 toolDouble
      var data = obj.data; // 获得当前行数据
      // console.log(obj)
      if (obj.event === 'edit') {
        layer.open({
          title: '编辑文章 [' + data.title + '] ',
          type: 2,
          area: ['80%', '80%'],
          content: '/admin/article/update/id/' + data.id
        });
      } else if (obj.event === 'more') {
        // 更多 - 下拉菜单
        dropdown.render({
          elem: this, // 触发事件的 DOM 对象
          show: true, // 外部事件触发即显示
          data: [{
            title: '查看',
            id: 'detail'
          }, {
            title: '审核',
            id: 'examine'
          }, {
            title: '删除',
            id: 'del'
          }, {
            title: '[添加/取消]置顶',
            id: 'top'
          }, {
            title: '[添加/取消]加精',
            id: 'hot'
          }],
          click: function (menudata) {
            if (menudata.id === 'detail') {
              layer.open({
                title: '查看文章 [' + data.title + '] ',
                type: 2,
                area: ['80%', '80%'],
                content: "/index/article/index.html?art_id=" + data.id
              });
            } else if (menudata.id === 'del') {
              layer.confirm('真的删除文章 [' + data.title + '] 么', function (index) {
                layer.close(index);
                $.post('/admin/article/del', { id: data.id }, (res) => {
                  layer.msg('操作成功')
                  obj.del()
                })

              });
            } else if (menudata.id == 'top') {
              let obj = { is_top: 1, id: data.id, action: 2 }
              $.post('/admin/article/doUpdate', obj, (res) => {
                if (res.code == 200) {
                  layer.msg('操作成功', { time: 1200 })
                  table.reload('test')
                } else {
                  layer.msg('操作失败', { time: 1200 })
                }
              }, 'json')
            } else if (menudata.id == 'hot') {
              let obj = { is_hot: 1, id: data.id, action: 2 }
              $.post('/admin/article/doUpdate', obj, (res) => {
                if (res.code == 200) {
                  layer.msg('操作成功', { time: 1200 })
                  table.reload('test')
                } else {
                  layer.msg('操作失败', { time: 1200 })
                }
              }, 'json')
            } else if (menudata.id == 'examine') {
              $.post('/admin/article/doUpdate/action/2', {
                id: data.id
                , examine: 1
              }, (res) => {
                if (res.code == 200) {
                  layer.msg('操作成功', { time: 1200 })
                  table.reload('test')
                } else {
                  layer.msg('操作失败', { time: 1200 })
                }
              }, 'json')

            }
          },
          align: 'right', // 右对齐弹出
          style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
        })
      }
    });
    // 复选框 批量删除
    table.on('checkbox(test)', function (obj) {
      if (obj.checked) {
        delObj.push(obj)
      } else {
        delObj.pop(obj)
      }
    });
    // 行单击事件
    table.on('row(test)', function (obj) {
      //layer.closeAll('tips');
    });
    // 行双击事件
    table.on('rowDouble(test)', function (obj) {
    });

    // 单元格编辑事件
    table.on('edit(test)', function (obj) {
      var field = obj.field; // 得到字段
      var value = obj.value; // 得到修改后的值
      var data = obj.data; // 得到所在行所有键值
      // 值的校验
      if (field == 'sort') {
        var regPos = /^[0-9]+.?[0-9]*/
        if (!regPos.test(obj.value)) {
          layer.tips('输入的排序格式应为数字', this, { tips: 1 });
          return obj.reedit();
        } else {
          $.ajax({
            url: '/admin/article/doUpdate/action/2'
            , type: 'post'
            , data: {
              id: data.id
              , sort: obj.value
            }
            , dataType: 'json'
            , success: (res) => {
              /*  if (res.code == 200) {
                 layer.msg('修改成功', { icon: 6 })
               } else {
                 layer.msg('删除失败', { icon: 5 })
               }
*/
            }
          })
          table.reload('test', {
            where: {
            }
          })
        }
      }

      layer.msg('编辑成功');

      // 其他更新操作
      var update = {};
      update[field] = value;
      obj.update(update);
    });
  });
</script>

</body>

</html>